/*import '../../src/assets/jssip.js'
import audio from '../../static/audio/incoming-call-ringtone.wav'
import backAudio from '../../static/audio/ringbacktone.wav'*/
var MyWebrtc = function () {
  var MediaStreamTrack = null;
  var outgoingSession = null;
  var incomingSession = null;
  var currentSession = null;
  var getJsSipgetIp = null; //存取全局IP
  var getJsSipPhoneNumber = null; //存取全局号码
  var getJsSipgetPassWord = null; //存取全局密码
  var getstatus1 = null;
  var getstatus2 = null;
  var globalRegisteState = '未注册';//注册状态
  var globalCallPhoneStates = "未通话";//通话状态
  var judgeIsVoice = "";//判断是语音拨打还是视频拨打
  var Datas = null;
  var remoteView = null
  //var remoteView = null
  var selfViewWap = null
  URL = window.URL || window.webkitURL;
  var localStream = null;
  var userAgent = null;
  var videoCallBack = null
  var hideCallBack = null

  var session;
  var incomingCallAudio = new window.Audio('dist/audio/incoming-call-ringtone.wav');
  var ringbackAudio = new window.Audio('dist/audio/ringbacktone.wav');
  incomingCallAudio.muted = true
  incomingCallAudio.loop = true;
  ringbackAudio.muted=true
  ringbackAudio.loop = true;
  var remoteAudio = new window.Audio();
  remoteAudio.autoplay = true;

  var constraints = {
    audio: true,
    video: true
  };

  //jssip实例初始化
  this.jssipAgent = function (WEBSocket,JsSipPhoneNumber, JsSipgetIp, JsSipgetPassWord, remoteVideo, Registerstate, Callstate,callback,videoEleId,selfVideoEleId,showCallback,hideCallback) {
    getJsSipPhoneNumber = JsSipPhoneNumber;
    getJsSipgetIp = JsSipgetIp;
    getJsSipgetPassWord = JsSipgetPassWord;
    getstatus1 = Registerstate;
    getstatus2 = Callstate;
    if (videoEleId) {
      remoteView = videoEleId
    }
    if (selfVideoEleId) {
      selfViewWap = selfVideoEleId
    }

    if (showCallback) {
      videoCallBack = showCallback
      hideCallBack = hideCallback
    }
    
    var phoneNumber = JsSipPhoneNumber + "@";
    var getIp = JsSipgetIp;
    getJsSipgetIp = JsSipgetIp;
    // var lastPort = ":5060"
    //var sip_uri_ = (phoneNumber + getIp + lastPort).toString();
    var sip_uri_ = ("sip:" + phoneNumber + getIp).toString();
    //	var ws_uri_ = "ws://10.0.11.120:5066";
    //var _Ws = "wss://";
    //var _WsPort = ":7067";
    //var ws_uri_ = (_Ws + getIp + _WsPort).toString();
    var ws_uri_ = WEBSocket
    //var sip_password_ = document.getElementById('JsSipgetPassWord').value;
    var sip_password_ = JsSipgetPassWord;
    //	var sip_password_ = "1234";
    var transport = ws_uri_.split("://")[0]
    JsSIP.C.SESSION_EXPIRES = 120, JsSIP.C.MIN_SESSION_EXPIRES = 120;
    var socket = new JsSIP.WebSocketInterface(ws_uri_);
    var configuration = {
      sockets: [socket],
      uri: sip_uri_,
      register: true,
      password: sip_password_,
      contact_uri: sip_uri_ + ';transport='+transport,
      ws_servers: ws_uri_
      //session_timers: false
    };

    userAgent = new JsSIP.UA(configuration);

    userAgent.on('registered', function (data) {
      console.info("registered: ", data.response.status_code, ",", data.response.reason_phrase);
      //注册状态显示
      if (getstatus1) {
        getstatus1.innerText = "已注册";
      }
      globalRegisteState = "已注册";
      callback(true)
    });
    //未注册
    userAgent.on('unregistered', function (e) {
      console.log("未注册", e);
      if (getstatus1) {
        getstatus1.innerText = "未注册";
      }
      globalRegisteState = "未注册";
    });
    userAgent.on('registrationFailed', function (data) {
      console.log("registrationFailed, ", data);
      //注册状态显示
      if (getstatus1) {
        getstatus1.innerText = "注册失败";
      }
      globalRegisteState = "注册失败";
      callback(false)
    });
    //1.在注册到期之前发射几秒钟。如果应用程序没有为这个事件设置任何监听器，JsSIP将像往常一样重新注册。
    userAgent.on('registrationExpiring', function () {

      //过期之后将自动重新注册
      console.warn("registrationExpiring");
      //重新注册
      userAgent.register();
      //jssipAgent(JsSipPhoneNumber,JsSipgetIp,JsSipgetPassWord,remoteVideo,status1,status2);
    });
    //为传入或传出的会话/呼叫
    userAgent.on('newRTCSession', function (data) {
      /*
           var newSession = data.session;
           if(session){ // hangup any existing call
               session.terminate();
           }
           session = newSession;
     */

      if (data.originator == 'remote') { //incoming call

        //alert("请选择接听按钮");
        incomingSession = data.session;
        Datas = data.session;
        //在这儿可以添加一个弹出对话框，选择接听或拒绝电话
        /*
        data.session.answer({
              'mediaConstraints': constraints,
              'mediaStream': null
        });
        //通话状态
        //判读语音接听方式
        console.log("judgeIsVoice",judgeIsVoice);
        Callstate.innerText = "通话中";
        globalCallPhoneStates = "通话中";
        */
//				if (judgeIsVoice) {
//					Callstate.innerText = "语音接听";
//				globalCallPhoneStates = "语音接听";
//				getRemoteVideo.src = '';
//				}else{
//					Callstate.innerText = "视频接听";
//				globalCallPhoneStates = "视频接听";
//				}


      } else {
        console.info("outgoingSession");
        outgoingSession = data.session;
        outgoingSession.on('connecting', function (data) {
          //通话状态
          if (getstatus2) {
            getstatus2.innerText = "连接中";
          }
          globalCallPhoneStates = "连接中";
          currentSession = outgoingSession;
          outgoingSession = null;
        });

      }
      //远程挂断事件
      data.session.on("ended", function (data) {
        hideCallBack()

        //通话状态
        if (Callstate) {
          Callstate.innerText = "已挂断";
        }
        globalCallPhoneStates = "已挂断";

        if (!judgeIsVoice) {
          var selfDom = document.getElementById(selfViewWap)
        if (selfDom && selfDom.srcObject) {
          selfDom.pause()
          selfDom.srcObject.getTracks()[0].stop()
          //selfViewWap.srcObject.getTracks()[1].stop()
        }
          MediaStreamTrack && MediaStreamTrack.stop()
      }
      });
      data.session.on('accepted', function (data) {
        if (data.originator == 'remote') {
          currentSession = incomingSession;
          incomingSession = null;
          console.info("setCurrentSession - ", currentSession);
          //通话状态
          if (getstatus2) {
            getstatus2.innerText = "通话中";
          }
          globalCallPhoneStates = "通话中";
        }
      });
      data.session.on('confirmed', function (data) {

        if (data.originator == 'remote' && currentSession == null) {
          currentSession = incomingSession;
          incomingSession = null;
          console.info("setCurrentSession - ", currentSession);
          //通话状态
          if (getstatus2) {
            getstatus2.innerText = "通话中";
          }
          globalCallPhoneStates = "通话中";

        }
      });
      data.session.on('sdp', function (data) {
        //data.sdp = data.sdp.replace('UDP/TLS/RTP/SAVPF', 'RTP/SAVPF');
        //console.info('onSDP, changed sdp - ', data.sdp);
      });
      data.session.on('progress', function (data) {
        if (data.originator == 'remote') {
          //通话状态
          //status2.innerText = "通话中";
        }
      });

      data.session.on('peerconnection', function (data) {
        data.peerconnection.onaddstream = function (ev) {
          ringbackAudio.muted=false
          ringbackAudio.pause()
          if (!judgeIsVoice) {
            videoCallBack(()=>{
              var videoDom = document.getElementById(remoteView)
              videoDom.srcObject = ev.stream
              remoteAudio.srcObject = ev.stream
              nativeVideo()
            })
            
          }else{
            remoteAudio.srcObject = ev.stream
          }
          //remoteAudio.srcObject = ev.stream
          //remoteView.src = URL.createObjectURL(ev.stream);
        };

      });

      data.session.on('addstream', function (e) {
        console.info('on addstream - ');
        incomingCallAudio.muted=false
        incomingCallAudio.pause();
        /*if (!judgeIsVoice) {
          remoteView.srcObject = e.stream
        }else{
          remoteAudio.srcObject = e.stream;
        }*/
      });

      data.session.on('failed', function (e) {
        console.info('on failed - ');
        if (incomingSession != null) {
          incomingCallAudio.muted=false
          incomingCallAudio.pause();
          incomingSession = null;
        }
      });

      if (data.session.direction === 'incoming') {
        remoteAudio.muted = false
        incomingCallAudio.muted=false
        incomingCallAudio.play();
      }


    });

    console.info("call register");
    userAgent.start();
  }

  // Register callbacks to desired call events
  var eventHandlers = {
    'progress': function (e) {
      console.log('call is in progress');
      getstatus2.innerText = "连接中";
      globalCallPhoneStates = "连接中";
    },
    'failed': function (e) {
      console.log('call failed: ', e);

      if (e.cause == "Busy") {
        getstatus2.innerText = "用户正忙";
        globalCallPhoneStates = "用户正忙";
      } else {
        //通话状态
        getstatus2.innerText = "拨打失败";
        globalCallPhoneStates = "拨打失败";

      }
    },
    'ended': function (e) {
      //隐藏本地视频区域
      //selfViewWap.style.display = "none";
      console.log('call ended : ', e);
      //通话状态
      getstatus2.innerText = "已挂断";
      globalCallPhoneStates = "已挂断";
    },

    'confirmed': function (e) {
      ringbackAudio.muted=false
      ringbackAudio.pause()
      console.log('call confirmed');
    }
  };

  //语音拨打
  this.JsSip_VoiceCall = function (callPhone, isVoice) {
    judgeIsVoice = isVoice;//判断是语音拨打还是视频拨打
    //var sip_phone_number_ ="sip:1000@10.0.11.120:5060";
    if (!isVoice) {
      judgeIsVoice = false
    }
    var sip = "sip:";
    var getIp = getJsSipgetIp;
    var sip_phone_number_ = (sip + callPhone + "@" + getIp).toString();
    console.log(sip_phone_number_);

    var options = {
      'eventHandlers': eventHandlers,
      'mediaConstraints': {
        audio:true,
        video:judgeIsVoice
      },
      'mediaStream': null
    };
    outgoingSession = userAgent.call(sip_phone_number_, options);
  }
  //语音接听
  this.VoiceAnsWter = function (isVideo) {
    incomingCallAudio.muted=false
    incomingCallAudio.pause();
    judgeIsVoice = !isVideo
    Datas.answer({
      'mediaConstraints': {
        'audio': true,
        "video": isVideo
      },
      'mediaStream': null
    });
    if (getstatus2) {
      getstatus2.innerText = "通话中";
    }
    globalCallPhoneStates = "通话中";
  }

  //获取本地视频
  function nativeVideo(){
    navigator.mediaDevices.getUserMedia({
      audio: false,
      video:{
        faceMode: 'user'
      }
    }).then(stream=>{
      var selfDom = document.getElementById(selfViewWap)
      selfDom.srcObject = stream
    }).catch(error=>{
      console.error(error)
    })
  }

  //挂断
  this.JsSip_hangUpPhone = function () {

    //关闭本地摄像头
    //this.closeLocalCapature();
    //userAgent.stop();//保存当前的注册状态并在正常注销并终止活动会话（如果有）后断开与信令服务器的连接。
    var options = {
      'status_code':486
    };

    if (incomingSession != null) {
      incomingCallAudio.muted=false
      incomingCallAudio.pause();
      incomingSession.terminate(options);
    } else {
      userAgent.terminateSessions(options); //终止当前对话
    }
    //通话状态
    if (getstatus2) {
      getstatus2.innerText = "已挂断";
    }
    globalCallPhoneStates = "已挂断";
    //当挂断电话要重新调用注册接口
    //this.jssipAgent(getJsSipPhoneNumber,getJsSipgetIp,getJsSipgetPassWord,getRemoteVideo,getstatus1,getstatus2);
    if (!judgeIsVoice) {
      var selfDom = document.getElementById(selfViewWap)
      if (selfDom && selfDom.srcObject) {
        selfDom.pause()
        selfDom.srcObject.getTracks[0].stop()
        //selfViewWap.srcObject.getTracks[1].stop()
      }
      MediaStreamTrack && MediaStreamTrack.stop()
    }
  }
  //关闭本地摄像头
	this.closeLocalCapature = function () {
    var selfDom = document.getElementById(selfViewWap)
    if (selfDom && selfDom.srcObject) {
        selfDom.pause()
        selfDom.srcObject.getTracks[0].stop()
        //selfViewWap.srcObject.getTracks[1].stop()
      }
		MediaStreamTrack && MediaStreamTrack.stop();
	}
  //注销
  this.JsSip_clearRegested = function () {
    var options = {
      all: true
    };
    userAgent.unregister(options);
    console.log('unregister')
    //userAgent.stop();//保存当前的注册状态并在正常注销并终止活动会话（如果有）后断开与信令服务器的连接。
  }
  //注册状态
  this.getRegisterState = function () {
    return globalRegisteState;
  }
  //通话状态
  this.callPoneState = function () {
    return globalCallPhoneStates;
  }
}
